package jsu.ljy.lostandfind.dao.impl;

import jsu.ljy.lostandfind.dao.BaseDao;
import jsu.ljy.lostandfind.model.User;
import jsu.ljy.lostandfind.util.DBUtil;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

import org.springframework.stereotype.Repository;

/**
 * 用户数据访问实现类
 * 
 * <p>实现了用户相关的数据库操作，包括用户信息的增删改查等基本操作。</p>
 * 
 * @author 罗嘉毅
 * @version 1.0
 * @since 2024-03-21
 */
@Repository
public class UserDaoImpl implements BaseDao<User> {

    /**
     * 保存用户信息
     * 
     * @param user 用户信息
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public void save(User user) {
        String sql = "INSERT INTO users (username, password, phone, email, create_time) VALUES (?, ?, ?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getPhone());
            pstmt.setString(4, user.getEmail());
            pstmt.setTimestamp(5, new Timestamp(user.getCreateTime().getTime()));
            pstmt.executeUpdate();
            
            // 获取生成的主键
            try (ResultSet rs = pstmt.getGeneratedKeys()) {
                if (rs.next()) {
                    user.setId(rs.getLong(1));
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("保存用户信息失败", e);
        }
    }

    /**
     * 更新用户信息
     * 
     * @param user 用户信息
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public void update(User user) {
        String sql = "UPDATE users SET username=?, password=?, phone=?, email=? WHERE id=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, user.getUsername());
            pstmt.setString(2, user.getPassword());
            pstmt.setString(3, user.getPhone());
            pstmt.setString(4, user.getEmail());
            pstmt.setLong(5, user.getId());
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("更新用户信息��败", e);
        }
    }

    /**
     * 删除用户
     * 
     * @param id 用户ID
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public void delete(Long id) {
        String sql = "DELETE FROM users WHERE id=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, id);
            pstmt.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException("删除用户失败", e);
        }
    }

    /**
     * 根据ID查询用户
     * 
     * @param id 用户ID
     * @return 用户信息，不存在时返回null
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public User findById(Long id) {
        String sql = "SELECT * FROM users WHERE id=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setLong(1, id);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToUser(rs);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询用户失败", e);
        }
        return null;
    }

    /**
     * 查询所有用户
     * 
     * @return 用户列表
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    @Override
    public List<User> findAll() {
        String sql = "SELECT * FROM users ORDER BY create_time DESC";
        List<User> users = new ArrayList<>();
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql);
             ResultSet rs = pstmt.executeQuery()) {
            while (rs.next()) {
                users.add(mapResultSetToUser(rs));
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询用户列表失败", e);
        }
        return users;
    }

    /**
     * 根据用户名查询用户
     * 
     * @param username 用户名
     * @return 用户信息，不存在时返回null
     * @throws RuntimeException 当数据库操作失败时抛出
     */
    public User findByUsername(String username) {
        String sql = "SELECT * FROM users WHERE username=?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            try (ResultSet rs = pstmt.executeQuery()) {
                if (rs.next()) {
                    return mapResultSetToUser(rs);
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException("查询用户失败", e);
        }
        return null;
    }

    private User mapResultSetToUser(ResultSet rs) throws SQLException {
        User user = new User();
        user.setId(rs.getLong("id"));
        user.setUsername(rs.getString("username"));
        user.setPassword(rs.getString("password"));
        user.setPhone(rs.getString("phone"));
        user.setEmail(rs.getString("email"));
        user.setCreateTime(rs.getTimestamp("create_time"));
        return user;
    }
} 